<template>
  <jke-modal
      :visible.sync="jkeForm.visible"
      :width="1200"
      :title="jkeForm.title"
      :fullscreen.sync="jkeForm.fullscreen"
      :switchFullscreen="jkeForm.switchFullscreen"
    >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['基础管理', '班组管理']" :currentMenu="jkeForm.title"></crumbs>
    <div class="form-body">
      <a-card title="基础信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="班组编号" required>
            <a-input
              v-decorator="[
                'teamCode',
                {
                  rules: [
                    {
                      required: true,
                      message: '请输入班组编号或自动生成',
                    },
                    {
                      message: '该班组编号已存在',
                      validator: (rule, value, callback) =>
                        validateDuplicateValue('mess_team_group', 'team_code', value, queryId, callback),
                    },
                  ],
                },
              ]"
              placeholder="不输入则自动生成"
              :disabled="isEdit"
            />
            <span class="btn-text code-btn" @click="genEntityCode" v-if="!isEdit">自动生成</span>
          </a-form-item>
          <!-- </a-form> -->
          <!-- <a-form :form="form" @submit="handleSubmit" layout="vertical"> -->
          <a-form-item label="班组名称">
            <a-input
              v-decorator="['teamName', { rules: [{ required: true, message: '请输入班组名称' }] }]"
              placeholder="请输入班组名称"
              :maxLength="30"
            />
          </a-form-item>
          <a-form-item label="所属车间">
            <a-select
              v-decorator="['workshop', { rules: [{ required: true, message: '请选择所属车间' }] }]"
              placeholder="请选择" allowClear
            >
              <a-select-option :value="undefined">请选择</a-select-option>
              <a-select-option v-for="(item, key) in dictOptions" :key="key" :value="item.value">
                <span style="display: inline-block; width: 100%" :title="item.text || item.label">
                  {{ item.text || item.label }}
                </span>
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-card>
      <a-card title="班组成员" :bordered="false" style="margin-top: 12px">
        <a-col :span="24" style="margin-bottom: 38px">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="teamMembers.loading"
            :columns="teamMembers.columns"
            :dataSource="teamMembers.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"
          >

            <template v-slot:sysUserCode="props">
              <a-input :value="propsName(props)" placeholder="请选择" readOnly unselectable="on" @click="showDepUser(props)" :class="userSelected(props)?'has-value':''">
                <a-icon slot="suffix" type="close-circle" class="close-icon" theme="filled" @click="userFilter('', [], props)" />
                <a-icon slot="suffix" type="search" class="down-icon" />
              </a-input>
              <j-select-user-by-dep :ref="`selectUser${props.index}`" v-if="tempIndex == props.index" v-show="false" @close="close" @changeRow="(v, row) => userFilter(v, row, props)" v-model="props.value" :limit="5" :seldep='true' :modalWidth="1000" :multi="false"></j-select-user-by-dep>
            </template>
            <template v-slot:action="props">
              <!-- <a style="padding-left: 3px">编辑</a> -->
              <a-popconfirm
                title="是否删除?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(props)"
                @cancel="cancel"
              >
                <a style="padding-left: 3px;color:#F25643">删除</a>
              </a-popconfirm>
            </template>
          </j-editable-table>
        </a-col>
      </a-card>
      <a-card title="其他信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="备注" style="flex: 1">
            <a-textarea :maxLength="500" placeholder="请输入" auto-size v-decorator="['remark']" />
          </a-form-item>
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，每个大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
    </div>

    <div class="footer-submit form-footer">
      <a-button @click="goBack" class="submitBtn" style="margin-right: 10px"> 取消 </a-button>
      <a-button type="primary" :loading="loadingSubmit" class="submitBtn" @click="saveForm"> 提交 </a-button>
    </div>
  </jke-modal>
</template>
<script>
import { FormTypes } from '@/utils/JEditableTableUtil'
import crumbs from '@/components/crumbs.vue'
import { teamGroupAdd, getUserDict, getDictModel, teamGroupEdit, teamGroupQueryById } from '@/api/goodsManagement'
import { API } from '@/api/requestFzs'
import { integerNum, validateDuplicateValue } from '@/utils/util'
import FileUpload from '@/components/fileActions/FileUpload.vue'
export default {
  data() {
    return {
      jkeForm: {
        title: '新建班组',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      validateDuplicateValue, //自动生成编码
      queryId: '',
      loadingSubmit: false, //防止多次提交
      submitApi: teamGroupAdd,
      isEdit: false,
      dictOptions: '', //班组车间下拉数据
      attachment: '', //附件
      // 辅助单位
      refKeys: ['teamMembers'],
      tableKeys: ['teamMembers'],
      projectList: [],
      teamMembers: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '班组成员',
            key: 'sysUserCode',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'sysUserCode',
            width: '47%',
            defaultValue: '',
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空', // 提示的文本
              },
            ],
          },
          {
            title: '班组成员',
            key: 'sysUserId',
            type: FormTypes.hidden,
          },
          {
            title: '班组成员姓名',
            key: 'realName',
            type: FormTypes.hidden,
          },
          {
            title: '是否为负责人',
            key: 'role',
            type: FormTypes.select,
            options: [
              // 下拉选项
              { title: '是', value: '1' },
              { title: '否', value: '0' },
            ],
            placeholder: '请选择',
            width: '47%',
            defaultValue: '',
            validateRules: [
              {
                required: true, // 必填
                message: '${title}不能为空', // 提示的文本
              },
            ],
          },

          {
            title: '操作',
            width: '6%',
            key: 'action',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'action',
            defaultValue: '',
          },
        ],
      },
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      tempIndex: -1,
    }
  },
  components: {
    FileUpload,
    crumbs,
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
  },
  methods: {
    showDepUser(props) {
      this.tempIndex = props.index
      let ref_name = `selectUser${props.index}`
      this.$nextTick(() => {
        this.$refs[ref_name].onSearchDepUser()
      })
      console.log(props);
    },
    userSelected(props) {
      let obj = this.$refs.teamMembers.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      return obj.realName ? true : false
    },
    propsName(props) {
      let obj = this.$refs.teamMembers.getValuesSync({ validate: false, rowIds: [props.rowId] }).values[0]
      return obj.realName
    },
    // 取消选人
    close() {
      this.tempIndex = -1
    },
    /* 选人 */
    userFilter(v, row, props) {
      this.tempIndex = -1
      if (row.length > 0) {
        console.log(row);
        this.$refs[this.refKeys[0]].setValues([
          {
            rowKey: props.rowId, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              sysUserCode: v,
              sysUserId: row[0].id,
              realName: row[0].realname,
              role: '0'
            },
          },
        ])
        console.log(this.$refs[this.refKeys[0]].getValuesSync().values)
      } else {
        this.$refs[this.refKeys[0]].setValues([
          {
            rowKey: props.rowId, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              sysUserCode: '',
              sysUserId: '',
              realName: '',
              role: ''
            },
          },
        ])
        return
      }
      const { error, values } = this.$refs.teamMembers.getValuesSync({ validate: true })
      let idLength = 0
      values.forEach((item) => {
        if (item.sysUserId == row[0].id) {
          idLength++
        }
      })
      if (idLength == 2) {
        this.$antdMessage.error('该成员已存在')
        this.$refs.teamMembers.removeRows(props.rowId)
        this.$refs.teamMembers.setValues([
          {
            rowKey: props.rowId, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              sysUserCode: '',
              sysUserId: '',
              realName: '',
            },
          },
        ])
      }
    },
    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'MESS_TEAM_GROUP' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            teamCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    /* 获取编辑详情 */
    initForm(id) {
      Object.assign(this.$data, this.$options.data.call(this));
      this.jkeForm.visible = true
      this.getdata()
      this.queryId = id
      if (id) {
        this.jkeForm.title = '编辑班组'
        this.submitApi = teamGroupEdit
        this.isEdit = true
        teamGroupQueryById({ id: id }).then((res) => {
          if (res.code == 200) {
            this.form.setFieldsValue(res.result)
            this.attachment = res.result.attachment
            this.teamMembers.dataSource = res.result.teamGroupUserList
          }
        })
      } else {
        this.jkeForm.title = '新建班组'
      }
    },
    // 辅助单位下拉选择数据接口
    getdata() {
      getUserDict().then((res) => {
        let arr = []
        res.forEach((item) => {
          arr.push({
            value: item.id,
            title: item.realname,
          })
        })
        this.projectList = arr
        this.teamMembers.columns[0].options = arr
      })
      // 班组车间下拉字典数据
      getDictModel({ dictCode: 'mess_team_workshop' }).then((res) => {
        this.dictOptions = res.result
      })
    },
    // 分类下拉选择
    handleSelectClassify(value) {
      console.log(value)
      this.form.setFieldsValue({
        note: `Hi, ${value === 'male' ? 'man' : 'lady'}!`,
      })
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交
    saveForm() {
      const { error, values } = this.$refs.teamMembers.getValuesSync({ validate: true })
      console.log(values, 'values save')
      if (values.length > 0) {
        if (!error) {
          this.handleSubmit(values)
        }
      } else {
        this.$antdMessage.error('班组成员不能为空！')
      }
    },
    handleSubmit(tableValue) {
      this.form.validateFields((err, values) => {
        console.log(values, 'values form')
        if (!err) {
          // if (values.purchaseDate) {
          //   values.purchaseDate = moment(values.purchaseDate).format('YYYY-MM-DD HH:mm:ss')
          // }

          console.log(tableValue, 'tableValue')
          let parameters = {
            ...values,
            attachment: this.attachment,
            teamGroupUserList: tableValue,
          }
          console.log(this.teamMembers, 'this.teamMembers')
          console.log(parameters, 'parameters')
          if (this.isEdit) {
            parameters.id = this.queryId
          }
          this.loadingSubmit = true

          this.submitApi(parameters).then((res) => {
            if (res.code == 200) {
              let subMsg = this.isEdit ? '班组编辑成功！' : '班组创建成功！'
              this.$antdMessage.success(subMsg)
              this.$emit('refresh')
              this.goBack()
              this.loadingSubmit = false
            } else {
              this.$antdMessage.error(res.message)
              this.loadingSubmit = false
            }
          })
          console.log('Received values of form: ', values)
        }
      })
    },
    // 辅助单位-删除
    handleDelete(props) {
      let { rowId, target } = props
      target.removeRows(rowId)
    },
    cancel() {},
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
</style>
